package com.bowen.paycenter.controller;

import cn.hutool.core.convert.ConverterRegistry;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.bowen.paycenter.domain.PayInfo;
import com.bowen.paycenter.resultResponse.ApiResult;
import com.bowen.paycenter.service.IPayService;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import constant.PayStatusConstant;
import constant.PayTypeConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @ClassName WxPayController
 * @Description 微信支付
 * @Date 2020/12/3 18:40
 * @Author Rick Jen
 * TODO 小程序支付需要申请开通jsApi支付
 */
@RestController
@RequestMapping(value = "/pay/weChatPay")
@Slf4j
public class WxPayController {

    private static final ConverterRegistry CONVERTER_REGISTRY = ConverterRegistry.getInstance();

    private final static String QUEUE_PAY_NOTIFY = "payNotify";

    /**
     * 微信支付回调地址
     */
    @Value("${wx.notifyUrl}")
    private String notifyUrl;

    /**
     * 微信app支付appId
     */
    @Value("${wechat.app.appId}")
    private String weChatPayAppId;

    /**
     * WxJava封装的微信支付
     */
    private final WxPayService wxPayService;


    /**
     * 支付信息
     */
    private final IPayService payService;


    public WxPayController(WxPayService wxPayService, IPayService payService) {
        this.wxPayService = wxPayService;
        this.payService = payService;
    }

    /**
     * @Description 微信支付-app拉起支付
     * @author Rick Jen
     * @Date 2020/12/3 18:54
     * @Param orderId 订单号 建议雪花算法生成
     * @Param amount 订单金额
     * @Param transactionDescription 交易描述
     * @Param goodsName 商品标题
     * @Return
     * @Exception
     */
    @RequestMapping(value = "/toPayByWeChat", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ApiResult toPayByWeChat(@RequestParam("orderId") String orderId,
                                   @RequestParam("amount") BigDecimal amount,
                                   @RequestParam("transactionDescription") String transactionDescription,
                                   @RequestParam("goodsName") String goodsName
    ) throws WxPayException {

        // 创建支付订单
        int flag = payService.createPayInfo(PayInfo.builder()
                .orderNo(CONVERTER_REGISTRY.convert(Long.class, orderId))
                .payPlatform(PayTypeConstant.WX_PAY)
                .platformStatus(PayStatusConstant.UN_PAID)
                .payAmount(amount)
                .refundStatus(PayStatusConstant.DONT_REFUND)
                .refundAmount(BigDecimal.ZERO)
                .createTime(DateUtil.date())
                .updateTime(DateUtil.date())
                .build());
        if (flag < 1) {
            throw new RuntimeException("支付宝下单失败！");
        }
        // TODO 调用统一生成订单接口
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setAppid(weChatPayAppId);
        orderRequest.setSignType(WxPayConstants.SignType.MD5);
        // 订单信息主体
        orderRequest.setBody(goodsName + "/n" + transactionDescription);
        orderRequest.setOutTradeNo(orderId);
        orderRequest.setTradeType(WxPayConstants.TradeType.APP);
        // 微信支付价格单位：分
        orderRequest.setTotalFee(BaseWxPayRequest.yuanToFen(CONVERTER_REGISTRY.convert(String.class, amount)));
        Date now = DateUtil.date();
        //10分钟后
        Date afterDate = DateUtil.offset(now, DateField.MINUTE, 10);
        orderRequest.setTimeStart(DateUtil.format(now, "yyyyMMddHHmmss"));
        orderRequest.setTimeExpire(DateUtil.format(afterDate, "yyyyMMddHHmmss"));
        orderRequest.setNotifyUrl(notifyUrl + "/api/weChatPay/notifyWxPay");
        orderRequest.setSpbillCreateIp("0.0.0.0");
        Object order = wxPayService.createOrder(orderRequest);
        return ApiResult.success("微信拉起支付成功！",order);
    }


}
